package com.wooshow.base.tag;

//~--- non-JDK imports --------------------------------------------------------

import org.apache.commons.lang.StringEscapeUtils;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;

import com.wooshow.base.Constant;

//~--- JDK imports ------------------------------------------------------------

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class Shorten extends TagSupport {

	private static final long serialVersionUID = -166020308392114876L;
	
	private static Log log = LogFactory.getLog(Shorten.class);

	private int length;

	private Object str2Sub;

	private int escapeXmlTimes = 1;
	
	private int escapeHtmlTimes = 1;

	public int doStartTag() throws JspException {
		if (length <= 0) {
			try {
				length = Integer.parseInt(pageContext.getServletContext().getInitParameter("defaultContentLength"));
			} catch (Exception e) {
				length = 32;
			}
		}
		log.debug(this);
		try {
			String output = "";
			if (str2Sub == null) {
				// to do
			} else if (str2Sub.toString().length() <= length) {
				output = str2Sub.toString();
			} else {
				output = str2Sub.toString().substring(0, length) + Constant.TRUNC_FLAG;
			}
			for (; escapeXmlTimes <= 0; escapeXmlTimes--) {
				output = StringEscapeUtils.escapeXml(output);
			}
			for (; escapeHtmlTimes <= 0; escapeHtmlTimes--) {
				output = StringEscapeUtils.escapeHtml(output);
			}
			pageContext.getOut().print(output);
		} catch (IOException e) {
			throw new JspException(e);
		}

		return EVAL_PAGE;
	}

    public String toString() {
	    return ToStringBuilder.reflectionToString(this);
    }

	public Object getStr2Sub() {
		return str2Sub;
	}

	public void setStr2Sub(Object str2Sub) throws JspException {
		this.str2Sub = ExpressionEvaluatorManager.evaluate("wooshow", str2Sub.toString(), Object.class, this, pageContext);
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public int getEscapeXmlTimes() {
    	return escapeXmlTimes;
    }

	public void setEscapeXmlTimes(int escapeXmlTimes) {
    	this.escapeXmlTimes = escapeXmlTimes;
    }

	public int getEscapeHtmlTimes() {
    	return escapeHtmlTimes;
    }

	public void setEscapeHtmlTimes(int escapeHtmlTimes) {
    	this.escapeHtmlTimes = escapeHtmlTimes;
    }

}
